using System;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Comteck.Winforms.Forms;
using ZXing;
using ZXing.QrCode;

namespace Comteck.Winforms.Dialog {
  /// <summary>
  /// 二维码
  /// </summary>
  public partial class FrmQRCodeDialog : FrmBase {

    #region field

    /// <summary>
    /// 二维码的值
    /// </summary>
    public string Key { get; set; }

    /// <summary>
    /// 二维码的连接
    /// <para>0.待生成二维码 1.二维码链接</para>
    /// </summary>
    public int Type { get; set; } = 0;

    #endregion

    #region ctor

    /// <summary>
    /// ctor
    /// </summary>
    public FrmQRCodeDialog() {
      InitializeComponent();
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="key"></param>
    /// <param name="type"></param>
    public FrmQRCodeDialog(string key, int type) : this() {
      this.Key = key;
      this.Type = type;
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="key"></param>
    /// <param name="type"></param>
    public FrmQRCodeDialog(string key, int type, string text) : this(key, type) {
      this.Text = text;
    }

    #endregion

    #region form load

    /// <summary>
    /// 
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void FrmQRCodeDialog_Load(object sender, EventArgs e) {
      if (this.DesignMode) {
        return;
      }

      // 根据类型分别显示二维码
      switch (this.Type) {
        case 0:
          // 直接生成对象
          this.ShowDirect();
          break;
        case 1:
          this.ShowByKey();
          break;
        default:
          break;
      }
    }

    /// <summary>
    /// 
    /// </summary>
    private void ShowDirect() {
      // 二维码参数
      var options = new QrCodeEncodingOptions() {
        CharacterSet = "UTF-8", // 设置内容编码 UTF-8
        DisableECI = true, //
        Width = pictureBox1.Width, // 宽度
        Height = pictureBox1.Height, // 高度
        Margin = 1, // 设置二维码的边距,单位不是固定像素
      };

      // 条码对象
      var writer = new BarcodeWriter {
        Format = BarcodeFormat.QR_CODE,
        Options = options,
      };

      // 填写值
      pictureBox1.Image = writer.Write(this.Key);
    }

    /// <summary>
    /// 
    /// </summary>
    private async void ShowByKey() {
      var webreq = System.Net.WebRequest.Create(this.Key);

      using (var response = await webreq.GetResponseAsync()) {
        using (var stream = response.GetResponseStream()) {
          pictureBox1.Image = Image.FromStream(stream);
          pictureBox1.SizeMode = PictureBoxSizeMode.Zoom;
        }
      }
    }

    #endregion

  }
}
